
class_name UnitAction
extends Node

## unit 的行动组件
## 攻击，移动功能在此组件实现

## 组件的装载者
@onready var master: Unit = null




func _ready() -> void:
	master = get_parent()




func _enter_tree() -> void:
	master = get_parent()




## 攻击请求
func attack_request() -> void:
	if master.property.action_chance > 0 and master.property.attack_chance > 0:
		master.hide_action_ui()
		master.emit_signal("attack_request_signal", master)




## 移动请求
func move_request() -> void:
	if master.property.action_chance > 0 and master.property.move_chance > 0:
		master.hide_action_ui()
		master.emit_signal("move_request_signal", master)




## 执行移动
## 接受一条行动路径
## 还接受路径上的图块
func move_conduct(_path: PackedVector2Array, _cells: Dictionary) -> void:
	master.property.action_chance -= 1
	master.property.move_chance -= 1
	
	var start_position: Vector2 = master.position
	var start_cell: Dictionary = _cells[_path[0]]

	var tween: Tween = get_tree().create_tween()
	for index in range(1, _path.size()):
		# 移动动画
		tween.tween_property(master, "position", _path[index], 0.4)
		tween.tween_callback(func () -> void:
			# 调用图块的回调方法
			if _cells[_path[index]]["through_call"] != null:
				_cells[_path[index]]["through_call"].call(master)
			# 调用被动技能检测并传入参数
			master.skill.auto_skill_check({
				"class": "MOVE",
				"start_position": start_position,
				"start_cell": start_cell,
				"target_position": _path[index],
				"target_cell": _cells[_path[index]],
				"path": _path,
				"index": index
			})
			# 更新起始点
			start_position = _path[index]
			start_cell = _cells[_path[index]]
		)
	
	await tween.finished # 等待移动结束




## 执行攻击
## 接受一个攻击对象
func attack_conduct(_unit: Unit) -> void:
	# 消耗机会
	master.property.action_chance -= 1
	master.property.attack_chance -= 1
	
	var harm_dic: Dictionary = {
		"class": "ATTACK",
		"type": "ordinary",
		"state": "START",
		"target": _unit,
		"harm": master.property.ap_ordinary
	}
	
	# 调用技能 auto 检测
	# 因为字典保存与传递的是一个引用
	# 所以将 harm 加入被动技能参数方便更改伤害数值的技能
	master.skill.auto_skill_check(harm_dic)
	
	# 调用被攻击对象的方法受攻击方法
	_unit.property.under_attack(master, harm_dic)
	
	# 播放攻击动画
	await attack_animation(_unit.position)
	
	# 攻击结束的调用
	harm_dic["state"] = "END"
	await master.skill.auto_skill_check(harm_dic)




## 攻击动画
## * 这个方法只是一个过度方法
func attack_animation(_target: Vector2) -> void:
	var direction: Vector2 = master.position.direction_to(_target)
	var origin: Vector2 = master.icon.global_position
	
	var tween: Tween = get_tree().create_tween()
	tween.tween_property(master.icon, "global_position", master.icon.global_position + direction * 16, 0.25)
	tween.chain().tween_property(master.icon, "global_position", origin, 0.25)
	
	# 等待动画结束
	await tween.finished
